<template>
  <div class="art-full-height">
    <!-- 搜索栏 -->
    <ArtSearchBar
      v-model="searchForm"
      :items="formItems"
      :show-expand="true"
      @search="handleSearch"
      @reset="handleReset"
    />

    <ElCard class="art-table-card" shadow="never">
      <ArtTableHeader
        v-model:columns="columnChecks"
        v-model:showSearchBar="showSearchBar"
        :loading="loading"
        @refresh="refreshData"
      >
      </ArtTableHeader>

      <!-- 数据表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
        <!-- 小区图片列（仅显示第一张，若有多张则显示数量提示） -->
        <template #areaPhoto="{ row }">
          <div v-if="row.geoArea && row.geoArea.areaPhoto && row.geoArea.areaPhoto.length > 0" class="flex items-center gap-2">
            <ElImage
              :src="row.geoArea.areaPhoto[0].url"
              :preview-src-list="row.geoArea.areaPhoto.map((item: any) => item.url)"
              preview-teleported
              fit="cover"
              class="w-10 h-10"
            />
            <span v-if="row.geoArea.areaPhoto.length > 1" class="text-xs text-gray-500 ml-1">
              +{{ row.geoArea.areaPhoto.length - 1 }}张
            </span>
          </div>
          <span v-else class="no-image">暂无图片</span>
        </template>

        <!-- 用户状态 -->
        <template #recordUserStatus="{ row }">
          <ElTag :type="getUserStatusType(row.recordUserStatus)">
            {{ getUserStatusLabel(row.recordUserStatus) }}
          </ElTag>
        </template>

        <!-- 通行状态 -->
        <template #passStatus="{ row }">
          <span :class="getPassStatusClass(row.recordUserStatus)">
            {{ getPassStatusText(row.recordUserStatus) }}
          </span>
        </template>

        <!-- 操作 -->
        <template #operation="{ row }">
          <div class="flex justify-center">
            <ArtButtonTable type="view" @click="viewDetail(row)" title="查看" />
          </div>
        </template>
      </ArtTable>

      <!-- 查看对话框 -->
      <AreaViewDialog
        v-model="viewDialogVisible"
        :area-data="currentAreaData"
      />
    </ElCard>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, h } from 'vue'
  import { dayjs, ElMessage, ElMessageBox } from 'element-plus'
  import { useTable } from '@/composables/useTable'
  import ArtSearchBar from '@/components/core/forms/art-search-bar/index.vue'
  import ArtTable from '@/components/core/tables/art-table/index.vue'
  import AreaViewDialog from './modules/area-view-dialog.vue'
  import { recordUserAreaGetDataUsingPost, recordUserAreaPageDataUsingPost, RecordUserAreaVo, openApiNewUserPageDataUsingPost, geoAreaPageDataUsingPost } from '@/api'
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'

  // 类型定义
  interface SearchForm {
    userId: number | undefined
    areaId: number | undefined
    recordUserStatus: number | undefined
    recordTime: [string, string] | undefined
  }

  // 用户状态配置
  const USER_STATUS_CONFIG: any = {
    1: { label: '绿码', type: 'success' },
    2: { label: '黄码', type: 'warning' },
    3: { label: '红码', type: 'danger' },
    4: { label: '灰码', type: 'info' }
  } as const

  // 响应式数据
  const searchForm = ref<SearchForm>({
    userId: undefined,
    areaId: undefined,
    recordUserStatus: undefined,
    recordTime: undefined
  })

  // 用户列表（用于用户搜索选择框）
  const userList = ref<any[]>([])
  const userListLoading = ref(false)

  // 小区列表（用于小区搜索选择框）
  const areaList = ref<any[]>([])
  const areaListLoading = ref(false)

  // 获取用户列表
  const getUserList = async (keyword = '') => {
    if (keyword && keyword.length < 2) return
    
    userListLoading.value = true
    try {
      const params = {
        current: 1,
        size: 50, // 将size改为50
        newPhone: keyword,
        newName: keyword
      }
      
      const res = await openApiNewUserPageDataUsingPost({ body: params })
      if (res.list) {
        userList.value = res.list
      }
    } catch (error) {
      console.error('获取用户列表失败:', error)
      ElMessage.error('获取用户列表失败')
    } finally {
      userListLoading.value = false
    }
  }

  // 获取小区列表（显示所有小区，包括隐藏的）
  const getAreaList = async (keyword = '') => {
    if (keyword && keyword.length < 2) return
    
    areaListLoading.value = true
    try {
      const params = {
        current: 1,
        size: 50, 
      } as any
      
      // 如果关键字是数字，按ID搜索；否则按名称搜索
      if (keyword && /^\d+$/.test(keyword)) {
        params.id = parseInt(keyword)
      } else if (keyword) {
        params.areaName = keyword
      }

      
      const res = await geoAreaPageDataUsingPost({ body: params })
      if (res.list) {
        areaList.value = res.list
      }
    } catch (error) {
      console.error('获取小区列表失败:', error)
      ElMessage.error('获取小区列表失败')
    } finally {
      areaListLoading.value = false
    }
  }

  const viewDialogVisible = ref(false)
  const currentAreaData = ref<RecordUserAreaVo | null>(null)

  // 搜索表单配置
  const formItems = computed(() => [
    {
      key: 'userId',
      label: '人员',
      type: 'select',
      props: {
        placeholder: '请输入用户姓名或手机号搜索',
        clearable: true,
        filterable: true,
        remote: true,
        loading: userListLoading.value,
        'reserve-keyword': true,
        'remote-method': getUserList,
        options: userList.value.map((item: any) => ({
          label: `${item.newName} (${item.newPhone})`,
          value: item.id
        })),
        suffixIcon: h('i', { class: 'el-input__icon el-icon-arrow-down' })
      }
    },
    {
      key: 'areaId',
      label: '小区名',
      type: 'select',
      props: {
        placeholder: '请输入小区ID或名称搜索',
        clearable: true,
        filterable: true,
        remote: true,
        loading: areaListLoading.value,
        'reserve-keyword': true,
        'remote-method': getAreaList,
        options: areaList.value.map((item: any) => ({
          label: `${item.areaName}${item.areaUpFlag === 1 ? ' (隐藏)' : ''}`,
          value: item.id
        })),
        suffixIcon: h('i', { class: 'el-input__icon el-icon-arrow-down' })
      }
    },
    {
      key: 'recordUserStatus',
      label: '扫码状态',
      type: 'select',
      props: {
        placeholder: '请选择扫码状态',
        clearable: true,
        options: [
          { label: '绿码', value: 1 },
          { label: '黄码', value: 2 },
          { label: '红码', value: 3 },
          { label: '灰码', value: 4 }
        ]
      }
    },
    {
      key: 'recordTime',
      label: '时间',
      type: 'daterange',
      props: {
        type: 'daterange',
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期',
        valueFormat: 'YYYY-MM-DD',
        clearable: true
      }
    }
  ])

  // 使用 useTable 管理表格数据
  const {
    columns,
    columnChecks,
    data,
    loading,
    pagination,
    getData,
    searchParams,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    core: {
      apiFn: recordUserAreaPageDataUsingPost,
      apiParams: {
        body: {
          userId: undefined,
          areaId: undefined,
          recordUserStatus: undefined,
          recordTimeBegin: undefined,
          recordTimeEnd: undefined
        }
      },
      paginationWrapper: 'body', // 将分页参数包装到 body 对象中
      columnsFactory: () => [
        {
          prop: 'newUser.newName',
          label: '用户名',
          minWidth: 120
        },
        {
          prop: 'newUser.newPhone',
          label: '手机号',
          minWidth: 120
        },
        {
          prop: 'recordUserStatus',
          label: '用户状态',
          width: 100,
          useSlot: true
        },
        {
          prop: 'passStatus',
          label: '通行状态',
          width: 100,
          useSlot: true
        },
        {
          prop: 'recordTime',
          label: '通行时间',
          width: 200,
          align: 'center',
          headerAlign: 'center',
          formatter: (row: RecordUserAreaVo) => row.recordTime ? dayjs(row.recordTime).format('YYYY-MM-DD HH:mm:ss') : ''
        },
        {
          prop: 'geoArea.areaName',
          label: '小区名',
          minWidth: 150
        },
        {
          prop: 'recordAddress',
          label: '位置',
          minWidth: 200
        },
        {
          prop: 'recordDistance',
          label: '距离(米)',
          width: 100,
          align: 'center',
          headerAlign: 'center'
        },
        {
          prop: 'operation',
          label: '操作',
          width: 150,
          fixed: 'right',
          align: 'center',
          headerAlign: 'center',
          useSlot: true
        }
      ]
    },
    hooks: {
      onSuccess: (tableData: RecordUserAreaVo[]) => {
        // 处理小区图片数据
        data.value = tableData.map((item: RecordUserAreaVo) => {
          if (item.geoArea && item.geoArea.areaPhoto) {
            try {
              item.geoArea.areaPhoto = JSON.parse(item.geoArea.areaPhoto || '[]')
            } catch (e) {
              item.geoArea.areaPhoto = []
            }
          }
          return item
        })
      }
    }
  })

  const showSearchBar = ref(false)

  const handleSearch = () => {
    searchParams.body.userId = searchForm.value.userId || undefined
    searchParams.body.areaId = searchForm.value.areaId || undefined
    searchParams.body.recordUserStatus = searchForm.value.recordUserStatus || undefined
    
    // 处理时间范围
    if (searchForm.value.recordTime && searchForm.value.recordTime.length === 2) {
      searchParams.body.recordTimeBegin = searchForm.value.recordTime[0]
      searchParams.body.recordTimeEnd = searchForm.value.recordTime[1]
    } else {
      searchParams.body.recordTimeBegin = undefined
      searchParams.body.recordTimeEnd = undefined
    }
    
    getData()
  }

  // 重置搜索表单
  const handleReset = () => {
    // 重置本地搜索表单
    searchForm.value = {
      userId: undefined,
      areaId: undefined,
      recordUserStatus: undefined,
      recordTime: undefined
    }
    
    // 重置搜索参数
    searchParams.body.userId = undefined
    searchParams.body.areaId = undefined
    searchParams.body.recordUserStatus = undefined
    searchParams.body.recordTimeBegin = undefined
    searchParams.body.recordTimeEnd = undefined
    searchParams.body.current = 1
    
    // 重新获取数据
    getData()
  }

  const getUserStatusLabel = (status: number) => {
    return USER_STATUS_CONFIG[status]?.label || '未知'
  }

  const getUserStatusType = (status: number) => {
    return USER_STATUS_CONFIG[status]?.type || 'info'
  }

  // 获取通行状态文本
  const getPassStatusText = (status: number) => {
    return [1, 2].includes(status) ? '正常通行' : '未认证'
  }

  // 获取通行状态样式类
  const getPassStatusClass = (status: number) => {
    return [1, 2].includes(status) ? 'pass-normal' : 'pass-restricted'
  }

  const viewDetail = (row: RecordUserAreaVo) => {
    currentAreaData.value = row
    viewDialogVisible.value = true
  }
</script>

<style lang="scss" scoped>
  .services-list {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
  }

  .service-tag {
    margin: 2px;
  }

  .no-image {
    font-size: 12px;
    color: rgb(var(--art-text-gray-500));
  }

  .user-status-cell {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .pass-normal {
    color: var(--el-color-success);
  }

  .pass-restricted {
    color: var(--el-color-danger);
  }
</style>